import sys
import subprocess
from PySide2 import QtWidgets
from PySide2.QtWidgets import QMessageBox
import argparse

class ProcessManager:
	def __init__(self):
		self.processes = []

	def add_process(self, process):
		self.processes.append(process)

	def terminate_all(self):
		for proc in self.processes:
			try:
				if proc.poll() is None:
					proc.terminate()
					proc.wait(timeout=3)
			except (ProcessLookupError, subprocess.TimeoutExpired):
				try:
					proc.kill()
				except Exception as e:
					print(f"Error killing process {proc.pid}: {str(e)}")
		self.processes.clear()

def run_script(script_name, file_path, manager):
	"""Generic script execution function"""
	script_map = {
		"低开销演示": "./monitor_vbslite_ram_usage.py",
		"低时延演示": "./monitor_vbslite_e2e_latency.py",
		"高可靠演示": "./monitor_vbslite_packet_loss.py"
	}

	try:
		process = subprocess.Popen(
			[sys.executable, script_map[script_name], '-f', file_path],
			creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == 'win32' else 0
		)
		manager.add_process(process)
	except FileNotFoundError:
		QMessageBox.critical(None, "File Missing", f"Could not find {script_map[script_name]} file")
	except Exception as e:
		QMessageBox.critical(None, "Execution Error",
							 f"{script_name} execution failed:\n{str(e)}")

class DemoWindow(QtWidgets.QWidget):
	def __init__(self, file_path):
		super().__init__()
		self.setWindowTitle("VBSLite 性能演示工具")
		self.setGeometry(100, 100, 1200, 600)
		self.file_path = file_path
		self.process_manager = ProcessManager()

		self.init_ui()

		self.app = QtWidgets.QApplication.instance()
		self.app.aboutToQuit.connect(self.cleanup)

	def init_ui(self):
		layout = QtWidgets.QVBoxLayout(self)

		button_frame = QtWidgets.QWidget(self)
		button_layout = QtWidgets.QHBoxLayout(button_frame)

		self.create_button("低开销演示", button_layout)
		self.create_button("低时延演示", button_layout)
		self.create_button("高可靠演示", button_layout)

		layout.addWidget(button_frame)

	def create_button(self, text, layout):
		btn = QtWidgets.QPushButton(text)
		btn.setStyleSheet("""
			background-color: #4CAF50;
			color: white;
			font-family: Arial;
			font-size: 14px;
			padding: 10px 20px;
			min-width: 150px;
		""")
		btn.clicked.connect(lambda: run_script(text, self.file_path, self.process_manager))
		layout.addWidget(btn)

	def cleanup(self):
		self.process_manager.terminate_all()

	def closeEvent(self, event):
		self.cleanup()
		event.accept()

if __name__ == "__main__":
	parser = argparse.ArgumentParser(description='Pass log file path.')
	parser.add_argument('-f', '--file', required=True, help='Path to the log file')
	args = parser.parse_args()

	app = QtWidgets.QApplication(sys.argv)
	window = DemoWindow(args.file)
	window.show()
	sys.exit(app.exec_())